package com.lemon.ui.codemaker.component;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import javax.swing.ImageIcon;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;

import com.alibaba.fastjson.JSONArray;
import com.aliyun.core.utils.IOUtils;
import com.lemon.components.ant.util.ConfigUtil;
import com.lemon.ui.codemaker.CodeMaker;
import com.lemon.ui.codemaker.component.dto.RecentlyFileDto;
import com.xiaoleilu.hutool.io.FileUtil;

import lombok.experimental.UtilityClass;

@UtilityClass
public class RecentlyFile {

	public static String configFilePath;
	
	JMenuItem mntmNewMenuItem_13 = new JMenuItem("清除所有");
	static {
		mntmNewMenuItem_13.setIcon(new ImageIcon(RecentlyFile.class.getResource("/code/icon/clear.png")));
		List<RecentlyFileDto> items;
		try {
			items = JSONArray.parseArray(IOUtils.toUtf8String(new FileInputStream(initPath())), RecentlyFileDto.class);
			if(items!=null) {
				configFilePath = items.stream().max(new Comparator<RecentlyFileDto>() {
					@Override
					public int compare(RecentlyFileDto o1, RecentlyFileDto o2) {
						return (int)(o1.getLastOpen()-o2.getLastOpen());
					}
				}).get().getPath();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void addFilePath(String path,JMenuItem menuItem) {
		File configfile = initPath();
		try {
			List<RecentlyFileDto> items = JSONArray.parseArray(IOUtils.toUtf8String(new FileInputStream(configfile)), RecentlyFileDto.class);
			if(items==null) {
				items = new ArrayList<RecentlyFileDto>();
			}
			RecentlyFileDto recentlyFileDto = items.stream().filter(item->item.getPath().equals(path)).findAny().orElse(null);
			if(recentlyFileDto == null) {
				items.add(new RecentlyFileDto(path,new Date().getTime()));
			} else {
				recentlyFileDto.setLastOpen(new Date().getTime());
			}
			FileUtil.writeString(JSONArray.toJSONString(items, true), configfile, "utf-8");
		} catch (FileNotFoundException e) {
			JOptionPane.showMessageDialog(null, "文件未找到:"+e.getMessage(), "配置文件错误", JOptionPane.ERROR_MESSAGE);
		} catch (IOException e) {
			JOptionPane.showMessageDialog(null, "配置文件读取错误："+e.getMessage(), "配置文件错误", JOptionPane.ERROR_MESSAGE);
		}
	}

	public void loadMenus(JMenuItem menuItem,CodeMaker container) {
		File configfile = initPath();
		menuItem.removeAll();
		try {
			List<RecentlyFileDto> items = JSONArray.parseArray(IOUtils.toUtf8String(new FileInputStream(configfile)), RecentlyFileDto.class);
			items = items.stream()
	               .sorted(Comparator.comparingLong(RecentlyFileDto::getLastOpen).reversed())
	               .collect(Collectors.toList());
			if(items!=null) {
				for(RecentlyFileDto item:items) {
					JMenuItem addPathMenuItem = new JMenuItem(item.getPath());
					addPathMenuItem.setIcon(new ImageIcon(RecentlyFile.class.getResource("/code/icon/file.png")));
					addPathMenuItem.addActionListener(new ActionListener() {
						
						@Override
						public void actionPerformed(ActionEvent e) {
							try {
								ConfigUtil.getInstance(RecentlyFile.configFilePath).loadPropertiesFrom(e.getActionCommand());
								addFilePath(e.getActionCommand(),menuItem);
								container.initializeForm();
							} catch (IOException e1) {
								e1.printStackTrace();
							}
						}
					});
					menuItem.add(addPathMenuItem);
				}
			}
			menuItem.add(mntmNewMenuItem_13);
		} catch (FileNotFoundException e) {
			JOptionPane.showMessageDialog(null, "文件未找到:"+e.getMessage(), "配置文件错误", JOptionPane.ERROR_MESSAGE);
		} catch (IOException e) {
			JOptionPane.showMessageDialog(null, "配置文件读取错误："+e.getMessage(), "配置文件错误", JOptionPane.ERROR_MESSAGE);
		}
		if(mntmNewMenuItem_13.getActionListeners().length==0) {
			mntmNewMenuItem_13.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent e) {
					RecentlyFile.clearPath(menuItem);
				}
			});
		}
	}
	
	public String getLastConfigFilePath() throws Exception{
		List<RecentlyFileDto> items = JSONArray.parseArray(IOUtils.toUtf8String(new FileInputStream(initPath())), RecentlyFileDto.class);
		if(items==null) {
			return null;
		} else {
			configFilePath = items.stream().max(Comparator.comparingLong(RecentlyFileDto::getLastOpen)).get().getPath();
			return configFilePath;
		}
	}
	
	public void clearPath(JMenuItem menuItem) {
		File configfile = initPath();
		FileUtil.writeString("", configfile, "utf-8");
		menuItem.removeAll();
		menuItem.add(mntmNewMenuItem_13);
		JOptionPane.showMessageDialog(null, "成功", "清除配置文件", JOptionPane.INFORMATION_MESSAGE);
	}
	
	private File initPath() {
		String userHome = System.getProperty("user.home");
		File recentlyFileConfig = new File(userHome,"/codemaker/recentlyFile.json");
		if(!recentlyFileConfig.getParentFile().exists()) {
			recentlyFileConfig.getParentFile().mkdirs();
		}
		if(!recentlyFileConfig.exists()) {
			try {
				recentlyFileConfig.createNewFile();
			} catch (IOException e) {
				JOptionPane.showMessageDialog(null, "配置文件初始化错误", "配置文件错误", JOptionPane.ERROR_MESSAGE);
			}
		}
		return recentlyFileConfig;
	}
}
